#include "yktask.hpp"
#include <eosio/system.hpp>

void yktask::issuetask(name admin, name issuer, string desc, uint64_t bonus)
{
    //验证
    require_auth(admin);
    //表操作
    tasks tk(get_self(), admin.value);
    check(bonus > 0, "bonus must bigger than 0");

    //available_primary_key()
    tk.emplace(admin, [&](auto &g){
        g.taskid   =   tk.available_primary_key();
        g.issuer   =   issuer;
        g.hunter   =   "none"_n;
        g.status   =   0;
        g.desc     =   desc;
        g.tasktime =   current_block_time().to_string();
        g.bonus    =   bonus;
    });
}

void yktask::taketask(name admin, uint64_t taskid, name hunter)
{
    //验证
    require_auth(admin);
    //表操作
    tasks tk(get_self(), admin.value);

    auto itr = tk.find(taskid);

    check(itr != tk.end(), "task does not exists");
    check(itr->hunter == "none"_n, " task already by taked");
    check(itr->status == 0, "task's status not equal 0");

    tk.modify(itr, admin, [&](auto &g){
        g.hunter = hunter;
        g.status = 1; //接受状态
    });
}

void yktask::committask(name admin, uint64_t taskid, name hunter)
{
    //验证
    require_auth(admin);
    //表操作
    tasks tk(get_self(), admin.value);

    auto itr = tk.find(taskid);

    check(itr != tk.end(), "task does not exists");
    check(itr->hunter == hunter, " only task's hunter can do");
    check(itr->status == 1, "task's status not equal 1");

    tk.modify(itr, admin, [&](auto &g){
        g.status = 2; //提交状态
    });
}

void yktask::confirmtask(name admin, uint64_t taskid, name issuer, uint8_t status, string comment)
{
    //验证
    require_auth(admin);
    //表操作
    tasks tk(get_self(), admin.value);

    auto itr = tk.find(taskid);

    check(itr != tk.end(), "task does not exists");
    check(itr->issuer == issuer, " only task's issuer can do");
    check(itr->status == 2, "task's status not equal 2");

    tk.modify(itr, admin, [&](auto &g){
        if(status == 3) {
            // 确认通过
            g.status = status;
            g.comment = comment;
            // token 发送
        } else {
            g.status = status;
            g.comment = comment;
        }
    });
}

const yktask::task & yktask::querytask(name admin, uint64_t taskid)
{
    //验证
    require_auth(admin);
    //表操作
    tasks tk(get_self(), admin.value);
    auto itr = tk.find(taskid);
    check(itr != tk.end(), "task does not exists");

    return *itr;
}
